package com.cheyunkeji.er.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.citymodel.CarSourceCitySortAdapter;
import com.cheyunkeji.er.adapter.evaluate.CarSourceCitySelecterAdapter;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.CarSourceCityPinyinComparator;
import com.cheyunkeji.er.utils.PinyinUtils;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class AreaSelectActivity extends BaseActivity
    implements AdapterView.OnItemClickListener, SideBar.OnTouchingLetterChangedListener {

  public static final int LEVEL_TYPE_PROVINCE = 1;
  public static final int LEVEL_TYPE_CITY = 2;
  private static final String TAG = AreaSelectActivity.class.getSimpleName();

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.lv_content)
  ListView lvContent;

  @BindView(R.id.activity_area_select)
  LinearLayout activityAreaSelect;

  @BindView(R.id.sidebar)
  SideBar sidebar;

  private int CURRENT_LEVEL_TYPE = LEVEL_TYPE_PROVINCE;

  private ArrayList<CarInfo.CarSourceCity> dataList;

  private CarSourceCitySelecterAdapter adapter;

  //   省份排序后列表Adapter
  private CarSourceCitySortAdapter sortAdapter;

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_area_select);
    ButterKnife.bind(this);
  }

  @Override
  protected void initView() {
    vTopbar.setLeftBack();
    dataList = new ArrayList<>();
    adapter = new CarSourceCitySelecterAdapter(dataList, this);
    lvContent.setAdapter(adapter);
    lvContent.setOnItemClickListener(this);
  }

  @Override
  protected void initData() {
    if (null == getIntent().getSerializableExtra("PARENT_LEVEL_INFO")) {
      loadData(String.valueOf(LEVEL_TYPE_PROVINCE), "0");
      vTopbar.setTitle("选择省份");
      CURRENT_LEVEL_TYPE = LEVEL_TYPE_PROVINCE;
    } else {
      CarInfo.CarSourceCity upperLevelInfo =
          (CarInfo.CarSourceCity) getIntent().getSerializableExtra("PARENT_LEVEL_INFO");
      if (TextUtils.equals(upperLevelInfo.getLevel(), "1")) {
        vTopbar.setTitle("选择城市");
      } else {
        vTopbar.setTitle("选择区县");
      }
      CURRENT_LEVEL_TYPE = LEVEL_TYPE_CITY;
      loadData(
          String.valueOf(Integer.valueOf(upperLevelInfo.getLevel()) + 1), upperLevelInfo.getId());
    }
  }

  private void loadData(String level, String upId) {

    Log.e(TAG, "loadData:  level : " + level + " \t UP ID : " + upId);

    HashMap<String, String> params = new HashMap<>();
    //        params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
    //        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("level", level);
    params.put("upid", upId);

    ApiClient.postForm(
        HttpConstants.PRE_SELECT_CHANNLE_GET_CAR_SOURCE_CITY_LIST,
        params,
        new RespCallback<List<CarInfo.CarSourceCity>>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CarInfo.CarSourceCity> data) {

            Log.e(TAG, "onSuccess: " + data.size());
            Log.e(TAG, "onSuccess: 获取成功");

            if (CURRENT_LEVEL_TYPE == LEVEL_TYPE_PROVINCE) {
              setProvinceList(data);
            } else {
              if (sidebar.getVisibility() == View.VISIBLE) {
                sidebar.setVisibility(View.GONE);
              }
              dataList.addAll(data);
              adapter.notifyDataSetChanged();
            }
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void setProvinceList(List<CarInfo.CarSourceCity> data) {
    if (null == data) {
      return;
    }
    dataList.addAll(data);
    //      设置首字母
    for (int i = 0; i < dataList.size(); i++) {
      dataList
          .get(i)
          .setLetter(
              String.valueOf(PinyinUtils.getPingYin(dataList.get(i).getName()).charAt(0))
                  .toUpperCase());
    }

    ArrayList<String> letterList = new ArrayList<>();

    for (int i = 0; i < dataList.size(); i++) {
      if (dataList.get(i).getLetter().matches("[A-Z]")
          && !letterList.contains(dataList.get(i).getLetter())) {
        letterList.add(dataList.get(i).getLetter());
      }
    }

    Collections.sort(letterList);
    sidebar.setIndexText(letterList);
    sidebar.setTextColor(Color.parseColor("#35404d"));
    sidebar.setVisibility(View.VISIBLE);

    Collections.sort(dataList, new CarSourceCityPinyinComparator());

    sortAdapter = new CarSourceCitySortAdapter(this, dataList);
    lvContent.setAdapter(sortAdapter);

    sidebar.setOnTouchingLetterChangedListener(this);
    lvContent.setOnItemClickListener(this);
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent();
    intent.putExtra("data", dataList.get(position));
    setResult(RESULT_OK, intent);
    MyApplication.getInstance().removeActivity(this.getClass());
  }

  @Override
  public void onTouchingLetterChanged(String s) {
    // 该字母首次出现的位置
    int position = sortAdapter.getPositionForSection(s.charAt(0));
    if (position != -1) {
      lvContent.setSelection(position);
    }
  }
}
